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p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ;
		
	$("#header").append(space).append("<button class=\"button\" id=\"logoutButton\" " +
		"style=\"text-align: left;font-size:16px;color:#770099;background-color:#FFFFFF;\"> log out</button>")
		;	
		
		

		
		$("#header button#logoutButton").click(function() {
			$.cookie("first",null) ;
			$.cookie("logged",false) ;
			login() ;
		 });
		
		
			if($.cookie("first") == null){
				login () ;
			}
		    // Initialize the activity check
		    	$.activity.init({
		        // Set interval check to every 60 seconds
		       interval: 1000*60,
		        intervalFn: function(info){
		            console.log('Interval Check - Last Active:', info.lastActive, ', Difference in milliseconds to current time:', info.diff);
		        },
		        // Set inactive check to every 20 mnts
		         inactive: 1000*60*20,
		        inactiveFn: function(){
		        	 $.cookie("first",null) ;
		        	 $.cookie("logged",false) ;
		        	login ();
		        	}
		    	});
		
		    // Either reactivate, or update the current timestamp when user clicks on the page
		    $(document).click(function(){
		        if ( $.activity.isActive() )
		            $.activity.update();
		        else
		            $.activity.reActivate();
		    });
		    
	 function login ()	{
		
		var dialog = $(DOM.loadHTML("okkam-extension", "html/login.html"));
		var elmts = DOM.bind(dialog);
	
	 	elmts.dialogHeader.text("Login to Google Refine");
	 	var level = DialogSystem.showDialog(dialog);
	
		elmts.username.focus();
		
		//elmts.dialogHeader.css("background-color","#f0fff0");
		elmts.dialogHeader.css("text-align","center");
		elmts.dialogBody.css("text-align","center");
		
		//elmts.dialogBody.css("color","blue");
	 	elmts.loginButton.click(function() {
	 		
	 		$.ajax({
				    type: "GET",
				    //url:  "http://192.168.234.122:9080//okkamrefine/login?callback=?",
				    url:  loginServerAddress,
				    data: {grusername:elmts.username.val(),grpassword:elmts.password.val()},
				    dataType: "json",
				    timeout: 1000,
				    success: function (response) {	
				    	if(elmts.password.val()==response["password"]){
				    		 $.cookie("first",false) ;
				    		 $.cookie("logged",true) ;
				    		DialogSystem.dismissUntil(level - 1);
				    	} 
				    	else
				    		alert (response["password"]);
				    }
	 			});	 	
	 });
	 	
	 	   elmts.password.keypress(function(e) {
	        if(e.which == 13) {
	            elmts.loginButton.focus().click();
	        }
	    });
	 	
	 	 	elmts.cancelButton.click(function() {
	 	 		$('div').hide();
	 }); 	
	 }
	 
	});
	
	});